//
//  DataManager.m
//  MSHD
//
//  Created by HCreater on 2017/12/13.
//  Copyright © 2017年 HCreater. All rights reserved.
//

#import "DataManager.h"

#define DictionaryAddObject(dictionary, key, value) [dictionary setObject:value forKey:key]

@interface DataManager()

@property (nonatomic, readwrite, strong) JQFMDB* dbMgr;

@property (nonatomic, readwrite, copy) NSArray* cityInfos;

@property (nonatomic, readwrite, strong) NSMutableDictionary* airValueInfo;
@property (nonatomic, readwrite, strong) NSMutableDictionary* waterValueInfo;

@property (nonatomic, readwrite, strong) NSDictionary* tPushData;

@end

@implementation DataManager

MHSingletonM(DataManager);

- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self initData];
    }
    
    return self;
}

- (void)initData
{
    _isInThirdLogin = NO;
    _isLoadingOver = NO;
    
    _phoneVCodeCaler = [[TimeCaler alloc] init];
    _pollutantDatas = [NSMutableArray array];
    
    _totalStationSearchKey = @"二次污普";
    
    [self _initCalerValue];
    
    [self _initPush];
}

- (void)_initCalerValue
{
    _airValueInfo = [NSMutableDictionary dictionary];
    _waterValueInfo = [NSMutableDictionary dictionary];
    
    DictionaryAddObject(_airValueInfo, @"二氧化硫", @"0.95");
    DictionaryAddObject(_airValueInfo, @"氮氧化物", @"0.95");
    DictionaryAddObject(_airValueInfo, @"一氧化碳", @"16.7");
    DictionaryAddObject(_airValueInfo, @"氯气", @"0.34");
    DictionaryAddObject(_airValueInfo, @"氯化氢", @"10.75");
    DictionaryAddObject(_airValueInfo, @"氟化物", @"0.87");
    DictionaryAddObject(_airValueInfo, @"氰化氢", @"0.005");
    DictionaryAddObject(_airValueInfo, @"硫酸雾", @"0.6");
    DictionaryAddObject(_airValueInfo, @"铬酸雾", @"0.0007");
    DictionaryAddObject(_airValueInfo, @"汞及其化合物", @"0.0001");
    DictionaryAddObject(_airValueInfo, @"一般性粉尘", @"4");
    DictionaryAddObject(_airValueInfo, @"石棉尘", @"0.53");
    DictionaryAddObject(_airValueInfo, @"玻璃棉尘", @"2.13");
    DictionaryAddObject(_airValueInfo, @"碳黑尘", @"0.59");
    DictionaryAddObject(_airValueInfo, @"铅及其化合物", @"0.02");
    DictionaryAddObject(_airValueInfo, @"镉及其化合物", @"0.03");
    DictionaryAddObject(_airValueInfo, @"铍及其化合物", @"0.0004");
    DictionaryAddObject(_airValueInfo, @"镍及其化合物", @"0.13");
    DictionaryAddObject(_airValueInfo, @"锡及其化合物", @"0.27");
    DictionaryAddObject(_airValueInfo, @"烟尘", @"2.18");
    DictionaryAddObject(_airValueInfo, @"苯", @"0.05");
    DictionaryAddObject(_airValueInfo, @"甲苯", @"0.18");
    DictionaryAddObject(_airValueInfo, @"二甲苯", @"0.27");
    DictionaryAddObject(_airValueInfo, @"苯并(a)芘", @"0.000002");
    DictionaryAddObject(_airValueInfo, @"甲醛", @"0.09");
    DictionaryAddObject(_airValueInfo, @"乙醛", @"0.45");
    DictionaryAddObject(_airValueInfo, @"丙烯醛", @"0.06");
    DictionaryAddObject(_airValueInfo, @"甲醇", @"0.67");
    DictionaryAddObject(_airValueInfo, @"酚类", @"0.35");
    DictionaryAddObject(_airValueInfo, @"沥青烟", @"0.19");
    DictionaryAddObject(_airValueInfo, @"苯胺类", @"0.21");
    DictionaryAddObject(_airValueInfo, @"氯苯类", @"0.72");
    DictionaryAddObject(_airValueInfo, @"硝基苯", @"0.17");
    DictionaryAddObject(_airValueInfo, @"丙烯腈", @"0.22");
    DictionaryAddObject(_airValueInfo, @"氯乙烯", @"0.55");
    DictionaryAddObject(_airValueInfo, @"光气", @"0.04");
    DictionaryAddObject(_airValueInfo, @"硫化氢", @"0.29");
    DictionaryAddObject(_airValueInfo, @"氨", @"9.09");
    DictionaryAddObject(_airValueInfo, @"三甲胺", @"0.32");
    DictionaryAddObject(_airValueInfo, @"甲硫醇", @"0.04");
    DictionaryAddObject(_airValueInfo, @"甲硫醚", @"0.28");
    DictionaryAddObject(_airValueInfo, @"二甲二硫", @"0.28");
    DictionaryAddObject(_airValueInfo, @"苯乙烯", @"25");
    DictionaryAddObject(_airValueInfo, @"二硫化碳", @"20");
    
    DictionaryAddObject(_waterValueInfo, @"总汞", @"0.0005");
    DictionaryAddObject(_waterValueInfo, @"总镉", @"0.005");
    DictionaryAddObject(_waterValueInfo, @"总铬", @"0.04");
    DictionaryAddObject(_waterValueInfo, @"六价铬", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"总砷", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"总铅", @"0.025");
    DictionaryAddObject(_waterValueInfo, @"总镍", @"0.025");
    DictionaryAddObject(_waterValueInfo, @"苯并(a)芘   ", @"0.0000003");
    DictionaryAddObject(_waterValueInfo, @"总铍", @"0.01");
    DictionaryAddObject(_waterValueInfo, @"总银", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"悬浮物(SS)", @"4");
    DictionaryAddObject(_waterValueInfo, @"生化需氧量(BOD5)", @"0.5");
    DictionaryAddObject(_waterValueInfo, @"化学需氧量(COD)", @"1");
    DictionaryAddObject(_waterValueInfo, @"总有机碳（TOC）", @"0.49");
    DictionaryAddObject(_waterValueInfo, @"石油类", @"0.1");
    DictionaryAddObject(_waterValueInfo, @"动植物油", @"0.16");
    DictionaryAddObject(_waterValueInfo, @"挥发酚", @"0.08");
    DictionaryAddObject(_waterValueInfo, @"总氰化物", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"硫化物", @"0.125");
    DictionaryAddObject(_waterValueInfo, @"氨氮", @"0.8");
    DictionaryAddObject(_waterValueInfo, @"氟化物", @"0.5");
    DictionaryAddObject(_waterValueInfo, @"甲醛", @"0.125");
    DictionaryAddObject(_waterValueInfo, @"苯胺类", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"硝基苯类", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"阴离子表面活性剂(LAS)    ", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"总铜", @"0.1");
    DictionaryAddObject(_waterValueInfo, @"总锌", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"总锰", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"彩色显影剂(CD-2)", @"0.2");
    DictionaryAddObject(_waterValueInfo, @"总磷", @"0.25");
    DictionaryAddObject(_waterValueInfo, @"元素磷(以P计) ", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"有机磷农药(以P计)", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"乐果", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"甲基对硫磷", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"马拉硫磷", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"对硫磷", @"0.05");
    DictionaryAddObject(_waterValueInfo, @"五氯酚及五氯酚钠(以五氯酚计)", @"0.25");
    DictionaryAddObject(_waterValueInfo, @"三氯甲烷", @"0.04");
    DictionaryAddObject(_waterValueInfo, @"可吸附有机卤化物(AOX)(以Cl计)", @"0.25");
    DictionaryAddObject(_waterValueInfo, @"四氯化碳", @"0.04");
    DictionaryAddObject(_waterValueInfo, @"三氯乙烯", @"0.04");
    DictionaryAddObject(_waterValueInfo, @"四氯乙烯", @"0.04");
    DictionaryAddObject(_waterValueInfo, @"苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"甲苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"乙苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"邻－二甲苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"对－二甲苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"间－二甲苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"氯苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"邻二氯苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"对二氯苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"对硝基氯苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"－二硝基氯苯", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"苯酚", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"间－甲酚", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"－二氯酚", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"三氯酚", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"邻苯二甲酸二丁脂", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"邻苯二甲酸二辛脂", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"丙烯腈", @"0.125");
    DictionaryAddObject(_waterValueInfo, @"总硒", @"0.02");
    DictionaryAddObject(_waterValueInfo, @"色度", @"5000");
    DictionaryAddObject(_waterValueInfo, @"大肠菌群数(超标)", @"3.3");
    DictionaryAddObject(_waterValueInfo, @"余氯量(用氯消毒的医院废水)", @"3.3");
    DictionaryAddObject(_waterValueInfo, @"0≦PH值<1", @"0.06");
    DictionaryAddObject(_waterValueInfo, @"1≦PH值<2", @"0.125");
    DictionaryAddObject(_waterValueInfo, @"2≦PH值<3", @"0.25");
    DictionaryAddObject(_waterValueInfo, @"3≦PH值<4", @"0.5");
    DictionaryAddObject(_waterValueInfo, @"4≦PH值<5", @"1");
    DictionaryAddObject(_waterValueInfo, @"5≦PH值<6", @"5");
    DictionaryAddObject(_waterValueInfo, @"9<PH值≦10", @"1");
    DictionaryAddObject(_waterValueInfo, @"10<PH值≦11", @"0.5");
    DictionaryAddObject(_waterValueInfo, @"11<PH值≦12", @"0.25");
    DictionaryAddObject(_waterValueInfo, @"12<PH值≦13", @"0.125");
    DictionaryAddObject(_waterValueInfo, @"13<PH值≦14", @"0.06");
    DictionaryAddObject(_waterValueInfo, @"牛", @"0.1");
    DictionaryAddObject(_waterValueInfo, @"猪", @"1");
    DictionaryAddObject(_waterValueInfo, @"鸡、鸭等家禽", @"30");
    DictionaryAddObject(_waterValueInfo, @"污水（小型企业）", @"1.8");
    DictionaryAddObject(_waterValueInfo, @"污水（饮食娱乐服务业）", @"0.5");
    DictionaryAddObject(_waterValueInfo, @"消毒床(医院)", @"0.14");
    DictionaryAddObject(_waterValueInfo, @"不消毒床(医院)", @"0.07");
    DictionaryAddObject(_waterValueInfo, @"消毒污水(医院)", @"2.8");
    DictionaryAddObject(_waterValueInfo, @"不消毒污水(医院)", @"1.4");
}

- (NSString*)taxCalStrFromEPInfos:(NSMutableDictionary*)epInfos name:(NSString*)name
{
    for (NSString* key in epInfos.allKeys)
    {
        if ([key containsString:name])
        {
            return epInfos[key];
            
            break;
        }
    }
    
    return @"";
}

- (CGFloat)taxCalValueFromEPInfos:(NSMutableDictionary*)epInfos name:(NSString*)name
{
    NSString* strValue = [self taxCalStrFromEPInfos:epInfos name:name];
    
    return [strValue floatValue];
}

- (NSString*)parentNameFromPollutantDatas:(PollutantData*)fPollutantData withSubName:(NSString*)subName
{
    for (PollutantData* subPData in fPollutantData.datas)
    {
        if ([subPData.pollutantName isEqualToString:subName])
        {
            return fPollutantData.pollutantName;
        }
        else
        {
            if (subPData.datas && subPData.datas.count>0)
            {
                if ([[self parentNameFromPollutantDatas:subPData withSubName:subName] isNotBlank])
                {
                    return fPollutantData.pollutantName;
                }
            }
        }
    }
    
    return @"";
}

- (void)reqCityData
{
    @weakify(self)
    /// 发起请求
//    [[AFNetWorkUtils racPOSTWthURL:url_interface_cityList params:@""] subscribeNext:^(id x) {
//        //成功返回(result class is NSDictionary)
//        
//        @strongify(self);
//        HDCitysData* datas = [HDCitysData modelWithJSON:x];
//        
//        _cityInfos = [datas.datas copy];
//    } error:^(NSError *error) {
//        //错误处理
//        NSLog(@"");
//    }];
}

- (ProvinceListData*)findCityDataBy:(NSString*)areaID
{
    for (ProvinceListData* curPPData in self.addrData.datas)
    {
        if (curPPData.datas.count > 0)
        {
            for (ProvinceListData* curSPData in curPPData.datas)
            {
                if ([curSPData.areaID isEqualToString:areaID])
                {
                    return curSPData;
                }
            }
        }
        else if ([curPPData.areaID isEqualToString:areaID])
        {
            return curPPData;
        }
    }
    
    return nil;
}

- (ProvinceListData*)findProvinceDataBy:(ProvincesListData*)addrDatas andAreaID:(NSString*)areaID
{
    for (ProvinceListData* curPPData in addrDatas.datas)
    {
        if ([curPPData.areaID isEqualToString:areaID])
        {
            return curPPData;
        }
    }
    
    return nil;
}

- (ProvinceListData*)findCityDataBy:(ProvincesListData*)addrDatas andAreaID:(NSString*)areaID
{
    for (ProvinceListData* curPPData in addrDatas.datas)
    {
        if (curPPData.datas.count > 0)
        {
            for (ProvinceListData* curSPData in curPPData.datas)
            {
                if ([curSPData.areaID isEqualToString:areaID])
                {
                    return curSPData;
                }
            }
        }
        else if ([curPPData.areaID isEqualToString:areaID])
        {
            return curPPData;
        }
    }
    
    return nil;
}

- (void)cleanDBMgr
{
    self.dbMgr = nil;
}

- (void)createDBMgr:(NSString*)dbName
{
    self.dbMgr = [JQFMDB shareDatabase:dbName];
    [self.dbMgr jq_createTable:@"ReadHistory" dicOrModel:[ArticleDBData class]];
    [self.dbMgr jq_createTable:@"DownloadHistory" dicOrModel:[ArticleDBData class]];
    [self.dbMgr jq_createTable:@"OfflineFileHistory" dicOrModel:[OfflineFileDBData class]];
}

- (void)saveOfflineFileHistory:(OfflineFileDBData*)aData
{
    if (self.dbMgr)
    {
        NSString* strWhereFormat = HCStrFormat(@"WHERE articleID = %d", (int)aData.articleID);
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            BOOL isSuc = [self.dbMgr jq_deleteTable:@"OfflineFileHistory" whereFormat:strWhereFormat];
            
            [self.dbMgr jq_insertTable:@"OfflineFileHistory" dicOrModel:aData];
        });
    }
}

- (void)saveDownloadHistory:(ArticleData*)aData
{
    if (self.dbMgr)
    {
        NSString* strWhereFormat = HCStrFormat(@"WHERE documentID = %d", (int)aData.documentID);
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            BOOL isSuc = [self.dbMgr jq_deleteTable:@"DownloadHistory" whereFormat:strWhereFormat];
            
            [self.dbMgr jq_insertTable:@"DownloadHistory" dicOrModel:aData.dbData];
        });
    }
}

- (void)saveHistory:(ArticleData*)aData
{
    if (self.dbMgr)
    {
        NSString* strWhereFormat = HCStrFormat(@"WHERE articleID = %d", (int)aData.articleID);
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            BOOL isSuc = [self.dbMgr jq_deleteTable:@"ReadHistory" whereFormat:strWhereFormat];
            
            [self.dbMgr jq_insertTable:@"ReadHistory" dicOrModel:aData.dbData];
        });
    }
}

- (void)_initPush
{
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_Push object:nil] subscribeNext:^(NSNotification* x)
    {
        NSNotificationCenter* notifyCenter = [NSNotificationCenter defaultCenter];
        
        NSDictionary* pushData = x.object;
        
        BOOL isFront = [pushData[@"IsFront"] boolValue];
        
        NSDictionary* userInfo = pushData[@"UserInfo"];
        
        NSString* strPushType = userInfo[@"type"];
        
        if ([strPushType isEqualToString:@"Article"] && !isFront)
        {
            [notifyCenter postNotificationName:Notify_Article_Push object:userInfo];
        }
        else if ([strPushType isEqualToString:@"SeedOrderRecord"])
        {
            [notifyCenter postNotificationName:Notify_Pay_Push object:userInfo];
        }
    }];
}

- (NSDictionary*)pushData
{
    return self.tPushData;
}

- (void)savePushData:(NSDictionary*)pushData
{
    self.tPushData = pushData;
}

- (ProvinceListData*)locationPLData
{
    NSArray* addrArr = [self.address componentsSeparatedByString:@"-"];
    NSString* cityName = addrArr[1];
    bool isFinded = NO;
    ProvinceListData* findPListData = nil;
    for (ProvinceListData* curPPListData in self.addrData.datas)
    {
        for (ProvinceListData* curSPListData in curPPListData.datas)
        {
            if ([cityName isEqualToString:curSPListData.name])
            {
                isFinded = YES;
                
                findPListData = curSPListData;
                
                break;
            }
        }
        
        if (isFinded)
            break;
    }
    
    return findPListData;
}

#pragma mark - 开屏广告
- (NSString*)loadingAdImgFileUrl
{
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    NSDictionary* saveInfo = [ud objectForKey:@"LoadingAdImg"];
    
    if (saveInfo == nil)
        return @"";
    
    return [self saveLoadingAdImgFileUrl];
}

- (NSString*)saveLoadingAdImgFileUrl
{
    return @"EPSys/LoadingImgPath.png";
}

- (NSString*)lastLoadingAdImgUrl
{
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    NSDictionary* saveInfo = [ud objectForKey:@"LoadingAdImg"];
    
    if (saveInfo==nil)
        return @"";
    
    return [saveInfo objectForKey:@"DownloadUrl"];
}

- (void)saveLastLoadingAdImgUrl:(NSString*)adImgUrl
{
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    
    NSMutableDictionary* saveInfo = [NSMutableDictionary dictionary];
    [saveInfo setObject:adImgUrl forKey:@"DownloadUrl"];
    
    [ud setObject:saveInfo forKey:@"LoadingAdImg"];
    [ud synchronize];
}

@end
